/*******************************************************************************
 * 导入excel（客户实销上报按日）
 ******************************************************************************/
function loadDataExcFxbyDay(dsId, flag) {   //导入按钮触发事件
    var cid = "";  //客户编号
    var importDate = "";    //获取导入日期
    if (dsId == "ds_fx_clientsales1" && flag == "fc") {   //客户实销上报(按日)
        cid = $('#' + flag + '_addWinTable input[qucln=CLIENT_ID]').val();
        importDate = $('#' + flag + '_addWinTable input[qucln=IMPORT_DATE]').val();
        CSID = $('#' + flag + '_addWinTable input[qucln=CS_ID]').val();
        if (cid == null || cid == "") {
            $.messager.alert("提示信息", "请选择客户!");
            return;
        }
        if (importDate == null || importDate == "") {
            $.messager.alert("提示信息", "请选择导入日期!");
            return;
        }
        //导入时进行的判断
        //1:每个客户每天只能导入一次不能重复导入
        $.ajax({
            type: 'post',
            url: _m_url + 'fxa/getFxCIdByDate',
            data: {'clientId': cid, 'Date': importDate, 'CSID': CSID},
            success: function (data) {
                if (data.rows.length > 0) {
                    $(importDate).val('');
                    //alert('亲，当前客户当天已上报过，请重新选择！');
                    $.messager.alert("提示信息", "亲，当前客户当天已上报过，请重新选择！");
                    return;
                } else {
                    if ($('#IMP_EXC_WIN').length > 0) {
                        $('#IMP_EXC_PARENT_PANEL').window('open');
                        var obj = document.getElementById("IMP_EXC_WIN");
                        document.body.removeChild(obj);
                    }
                    var div_box = document.createElement("DIV");
                    div_box.id = "IMP_EXC_WIN";
                    div_box.height = 100;
                    document.body.appendChild(div_box);
                    var dsid = $('#' + flag + '_SAVE_BUT').attr('dsid');
                    var keys = $('#' + flag + '_addWinTable input[qucln]');
                    var kvs = "";
                    for (var i = 0; i < keys.length; i++) {
                        if ($(keys[i]).attr('qucln').indexOf("ID") != -1 || $(keys[i]).attr('qucln').indexOf("MAN") != -1 || $(keys[i]).attr('qucln').indexOf("CODE") != -1) {
                            if ($(keys[i]).attr('value')) {
                                kvs += "`" + $(keys[i]).attr('qucln') + "`" + ":" + "`" + $(keys[i]).attr('value') + "`" + ",";
                            }
                        }
                    }
                    var width = document.documentElement.clientWidth;
                    var height = document.documentElement.clientHeight;
                    $('#IMP_EXC_WIN').load(_m_url + 'singlePages/pageToImportkh', {
                            'dsId': dsId,
                            'flag': flag,
                            'dsid': dsid
                        },
                        function () {
                            $("#download").attr("href", _m_url + "singlePages/dow?fileName=" + flag + ".xlsx");
                            $.parser.parse('#IMP_EXC_DG_PANEL');
                            $('#IMP_EXC_PARENT_PANEL').window({
                                width: 650,
                                height: 450,
                                draggable: true,
                                top: (height - 450) * 0.5,
                                left: (width - 650) * 0.5,
                                modal: true,
                                resizable: false,
                                closable: false,
                                collapsible: false,
                                maximizable: false,
                                minimizable: false
                            });
                        });
                    //loadDataExc(dsId,flag);
                    //initDataGrid(flag);
                    //importexcel(flag,dsId);
                }
            }
        });
    }

}


/***
 * 客户实销上报(按日)保存按钮方法
 * @param obj
 * @return
 */
function FCSave(obj) {
    var cid = "";  //客户编号
    var importDate = "";    //获取导入日期
    //客户实销上报(按日)
    cid = $('#fc_addWinTable input[qucln=CLIENT_ID]').val();
    importDate = $('#fc_addWinTable input[qucln=IMPORT_DATE]').val();
    CSID = $('#fc_addWinTable input[qucln=CS_ID]').val();
    if (cid == null || cid == "") {
        $.messager.alert("提示信息", "请选择客户!");
        return;
    }
    if (importDate == null || importDate == "") {
        $.messager.alert("提示信息", "请选择导入日期!");
        return;
    }
    //导入时进行的判断
    //1:每个客户每天只能导入一次不能重复导入
    $.ajax({
        type: 'post',
        url: _m_url + 'fxa/getFxCIdByDate',
        data: {'clientId': cid, 'Date': importDate, 'CSID': CSID},
        success: function (data) {
            if (data.rows.length > 0) {
                $(importDate).val('');
                //alert('亲，当前客户当天已上报过，请重新选择！');
                $.messager.alert("提示信息", "亲，当前客户当天已上报过，请重新选择！");
                return;
            } else {
                var CS_ID = $("#fc_addWinForm input[qucln='CS_ID']").val();
                if (!CS_ID) {
                    $(obj).attr('sou', 1);
                } else {
                    $(obj).attr('sou', 2);
                }
                common_save(obj);
            }
        }
    });
}


var hisbn = null;
function initDataGrid(flg) {
    // 初始化弹窗
    $('#manage_ap').window({
        title: '手动匹配',
        width: 545,
        height: 365,
        closed: false,
        closable: false
    });
    $('#manage_app').load(
        window.parent._index_path + 'model/importExcel/MataOrderName.jsp',
        {},
        function () {
        }
    );
    $('#manage_ap').window('close');
    // 初始化datadrid;
    $('#IMP_EXC_DATALIST').datagrid({
        iconCls: 'icon-save',
        width: 620,
        height: 360,
        striped: true,
        collapsible: true,
        autoRowHeight: false,
        sortOrder: 'desc',
        remoteSort: false,
        fixed: true,
        columns: [[
            {field: 'kk', checkbox: true},
            {field: "IS_PP", title: '是否匹配成功', formatter: convert},
            {field: "PP_DESC", title: '备注'},
            {field: "H_ISBN", title: '导入书号'},
            {field: "H_NAME", title: '匹配书名', width: 200},
// {field:"H_ID_MATCH",title:'匹配后商品',formatter:eval('window.parent.dz_productfmat')},
            {field: "H_PRICE", title: '定价'},
            {field: "H_AMOUNT", title: '导入数量'},
            {field: "SYSPICI", title: '匹配批次', hidden: true},
            {field: "H_ID", title: '商品id', hidden: true}
        ]],
        rowStyler: function (index, row) {
            if (row.IS_PP == 0) {
                return 'background-color:#bbddf5;';
            }
        },
        singleSelect: true,
        onSelect: function (rowIndex, rowData) {
        },
        // 双击执行效果
        onDblClickRow: function (index, field, value) {
            $(this).datagrid("selectRow", index);
            var hisbn = field.H_ISBN;
            var hname = field.H_NAME;
            var str = " <div id=\"kehxscjwin\" iconCls=\"icon-save\" title=\"商品(选择一条数据单击确定加入明细)\">" +
                "<span>书号:</span>" + "<input id=\"shuhao_\" type=\"text\" >" +
                "<span>书名:</span>" + "<input id=\"shuming_\" type=\"text\" >" +
                "&nbsp;<a   class=\"easyui-linkbutton  l-btn\" iconCls=\"icon-search\" onclick=\"search2__()\">" +
                "<span class=\"l-btn-left\">" +
                "<span class=\"l-btn-text\">查询</span>" +
                "</span>" +
                "</a>" +
                "&nbsp;<a  class=\"easyui-linkbutton  l-btn\" iconCls=\"icon-save\" onclick=\"commit2__()\">" +
                "<span class=\"l-btn-left\">" +
                "<span class=\"l-btn-text\">确定</span>" +
                "</span>" +
                "</a>" +
                "<table id=\"fxkeh_Datagrid\" style='width:450px;height:220px'>";
            str += "</table></div>";
            $("body").append(str);		// 拼接弹框的弹出层
            $("#kehxscjwin").window({
                width: 500,
                height: 300,
                modal: true,
                resizable: false,
                closable: true,
                collapsible: false,
                maximizable: false,
                minimizable: false
            });
            var shuhao = $("#shuhao_").val(hisbn);
            //查询方法
            search2__();
            $("#fxkeh_Datagrid").datagrid({
                singleSelect: true,			// 只允许选中一条数据
                fit: true,
                columns: [[
                    {field: 'H_ISBN', title: '书号', width: 150},
                    {field: 'H_NAME', title: '书名', width: 150},
                    {field: 'H_PRICE', title: '单价', width: 50},
                    {field: 'H_DISCOUNT', title: '折扣', width: 50, hidden: true},
                    {field: 'H_AMOUNT', title: '数量', width: 50, hidden: true},
                    {field: 'H_ID', title: '主键', width: 100, hidden: true},
                    {field: 'AMOUNT', title: '客户库存', width: 100, hidden: true}
                    //,
                    //{field: 'H_TAOZHUANG', title: '套装书名', width: 100, hidden: true},
                    //{field: 'C_CODE', title: '客户自编码', width: 100, hidden: true}
                ]]
            });
        }
    });
}
// 错误信息界面==>双击人工匹配界面,查询按钮响应
function search2__() {
    var shuhao = $("#shuhao_").val();
    var shuming = $("#shuming_").val();
    $.ajax({
        url: "singlePages/queryProductBYDAY",
        data: {'H_ISBN': shuhao, "H_NAME": shuming},
        success: function (data) {
            console.log(data);
            $("#fxkeh_Datagrid").datagrid('loadData', {"total": data.length, "rows": data});
        }
    });

}
// 错误信息界面==>双击人工匹配界面,确认按钮响应
function commit2__() {
    var flg = $("#_flg").val();
    var dsId = $("#" + flg + "_addItemDatagrid").attr("dsId");
    var row_error = $("#IMP_EXC_DATALIST").datagrid('getSelected');
    var pkidKey = $("#" + flg + "_addWinTable").find("input[vpk=T]").attr("qucln");
    var selrows = $("#fxkeh_Datagrid").datagrid('getSelected');
    var pkid = $("#" + flg + "_addItemDatagrid").find("input[qucln=" + pkidKey + "]").val();
    var oldRows = $("#" + flg + "_addItemDatagrid").datagrid("getRows");
    var row_error = $("#IMP_EXC_DATALIST").datagrid('getSelected');
    // 将人工匹配的row数据添加到明细
    var addRows = {};
    addRows[pkidKey] = pkid;
    addRows["H_ISBN"] = selrows.H_ISBN;//row_error
    addRows["H_NAME"] = selrows.H_NAME;
    addRows["H_PRICE"] = selrows.H_PRICE;
    addRows["H_AMOUNT"] = row_error.H_AMOUNT;
    addRows["AMOUNT"] = row_error.AMOUNT;//H_AMOUNT
    //addRows["H_TAOZHUANG"] = row_error.H_TAOZHUANG;
    //addRows["C_CODE"] = row_error.C_CODE;
    addRows["H_DISCOUNT"] = row_error.H_DISCOUNT;
    addRows["SORT_NUMBER"] = selrows.SORT_NUMBER;
    addRows["H_ID"] = selrows.H_NAME;//H_ID

    $("#" + flg + "_addItemDatagrid").datagrid('appendRow', addRows);
    var index = $("#IMP_EXC_DATALIST").datagrid('getRowIndex', row_error);
    console.log(index);
    $("#IMP_EXC_DATALIST").datagrid('deleteRow', index);
    // 关闭窗口
    $("#kehxscjwin").window('close');
}
function convert(value) {
    if (value == 1) {
        return '自动匹配成功';
    } else {
        return '自动匹配失败';
    }
}
// 保存所有匹配成功过的信息
function saveMateSuccessInfo(flag) {
    // 获取被更改的datagrid对象
    var lastDatagrid = $("#" + flag + "_addItemDatagrid");
    // 获取当前的datagrid对象
    var currentDatagrid = $("#IMP_EXC_DATALIST");
    var rows = currentDatagrid.datagrid("getRows");// 这段代码是获取当前页的所有行。
    var DISCOUNT = 0.3;
    var STOCK = null;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].IS_PP == 1) {
            lastDatagrid.datagrid('appendRow', {
                H_ID: rows[i].H_ID_MATCH,
                H_PRICE: rows[i].H_PRICE,
                H_ISBN: rows[i].H_ISBN,
                H_TYPE: rows[i].H_TYPE,
                H_AMOUNT: rows[i].H_AMOUNT,
                AMOUNT: rows[i].H_AMOUNT,
                H_DISCOUNT: DISCOUNT,
                H_NAME: rows[i].H_NAME,
                //H_TAOZHUANG: rows[i].H_TAOZHUANG,
                //C_CODE: rows[i].C_CODE,
                STOCK_ID: STOCK,
                SORT_NUMBER: i + 1
            });
        }
    }
    // 对当前导入到临时表的数据进行删除
    $.ajax({
        url: "singlePages/delsmataOrders",
        data: {'syspici': rows[0].SYSPICI},
        success: function (data) {
            currentDatagrid.datagrid('loadData', {total: 0, rows: []});
            $('#file').val('');
        }
    });
    // 清空grid
    $("#IMP_EXC_DATALIST").datagrid('loadData', {total: 0, rows: []});
    // 文件清空
    $("#file").val('');
    // 关闭当前panel
    $('#IMP_EXC_PARENT_PANEL').window('close');
}
// 返回
function importexcelBack() {
    // 文件清空
    $("#file").val('');
    $("#IMP_EXC_DATALIST").datagrid('loadData', {total: 0, rows: []});
    $('#IMP_EXC_PARENT_PANEL').window('close');
}
function importexcel(flg, dsid) {
    var cid = $('#fc_addWinTable input[qucln=CLIENT_ID]').val();
    var configStr = "AND CLIENT_ID= '" + $('#fc_addWinTable input[qucln=CLIENT_ID]').val() + "'";
    var xt_id = $('#fc_addWinTable input[qucln=CS_ID]').val();
    //根据dsid重新获取kvs
    var keyes = $('#' + flg + '_addWinTable input[qucln]');
    var kvs = "";
    for (var i = 0; i < keyes.length; i++) {
        if ($(keyes[i]).attr('qucln').indexOf("ID") != -1 || $(keyes[i]).attr('qucln').indexOf("MAN") != -1 || $(keyes[i]).attr('qucln').indexOf("IMPORT_DATE") != -1) {
            if ($(keyes[i]).attr('value')) {
                kvs += "`" + $(keyes[i]).attr('qucln') + "`" + ":" + "`" + $(keyes[i]).attr('value') + "`" + ",";
            }
        }
    }

    var keys = flg + "/" + dsid + "/" + kvs
    if ($("#file").val() != "" && $("#file").val() != null) {
        if ($("#file").val().indexOf(".xls") > 0
            || $("#file").val().indexOf(".xlsx") > 0
            || $("#file").val().indexOf(".XLS") > 0
            || $("#file").val().indexOf(".XLSX") > 0
        ) {
            var mask_kk = $("<div id='mask_kk' class=\"datagrid-mask\" style='z-index:99999;'></div>")
                .css({display: "block", width: "100%", height: $(window).height()})
                .appendTo("body");
            var mask_kkk = $("<div id='mask_kkk' class=\"datagrid-mask-msg\" style='z-index:100000;'></div>")
                .html("分析Excel数据中,请稍候...")
                .appendTo("body")
                .css({
                    display: "block",
                    left: ($(document.body).outerWidth(true) - 190) / 2,
                    top: ($(window).height() - 45) / 2
                });
            $.ajaxFileUpload({
                // 处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
                url: encodeURI('../..' + window.parent._index_path + 'singlePages/improtRetunInfofc?keys=' + keys),
                type: 'post',
                secureuri: false,                    // 是否启用安全提交,默认为false
                fileElementId: 'file',               // 文件选择框的id属性
                dataType: 'json',                    // 服务器返回的格式,可以是json或xml等
                data: {"cid": cid, "configStr": configStr, "xt_id": xt_id, "flg:": flg, "dsid:": dsid, "kvs:": kvs},
                success: function (data) {        // 服务器响应成功时的处理函数
                    var obj;
                    try {
                        obj = eval('(' + data.json + ')');
                    }
                    catch (e) {
                        alert('服务器已分析完毕excel,但数据有问题,请检查EXCEL!');
                        $('#mask_kkk').css("display", "none");
                        mask_kkk.remove();
                        mask_kk.remove();
                        return;
                    }
                    var dg;
                    // 回显错误信息
                    if (obj.errorData != undefined) {
                        dg = $('#IMP_EXC_DATALIST');
                        dg.css('overflow-x', 'auto');
                        dg.datagrid('loadData', {"total": obj.errorData.length, "rows": obj.errorData});
                    }
                    // 回显不能点击信息
                    if (obj.bad != undefined) {
                        dg = $('#IMP_EXC_DATALIST');
                        dg.css('overflow-x', 'auto');
                        dg.datagrid('loadData', {"total": obj.bad.length, "rows": obj.bad});
                    }
                    // 回显正确信息 appendRow
                    if (obj.successData != undefined) {
                        var successData = obj.successData;
                        dg = $("#" + flg + "_addItemDatagrid");
                        var dsId = $(dg).attr("dsId");
                        var length = $(dg).datagrid("getRows").length;
                        var oldRows = $(dg).datagrid("getRows");
                        if (document.getElementById("ischecked").checked == false) {
                            var hash = {};
                            var i = Number(0);
                            var index;
                            /***********************************************
                             * 导入的商品先进行重复商品的合并
                             */
                            while (i < successData.length) {
                                if (hash[successData[i].H_ID] != undefined && hash[successData[i].H_ID] != "") {
                                    var oldIndex = hash[successData[i].H_ID].split("_")[0];// 获取重复商品的下标
                                    successData[oldIndex].H_AMOUNT = Number(successData[index].H_AMOUNT) + Number(successData[oldIndex].H_AMOUNT);
                                    successData.splice(index, 1);
                                } else {
                                    hash[successData[i].H_ID] = i + "_" + successData[i].H_ID;
                                    i++;
                                    index = i;
                                }
                            }
                            /***********************************************
                             * 然后再和明细中原有的数据进行重复商品的数量合并
                             */
                            var cindex = Number(0);
                            var rows = new Array();
                            for (var i = 0; i < oldRows.length; i++) {
                                for (var j = 0; j < successData.length; j++) {
                                    if (oldRows[i].H_ID == successData[j].H_ID) {
                                        rows[cindex] = {
                                            INDEX: i + 1,
                                            H_ISBN: successData[j].H_ISBN,
                                            H_NAME: successData[j].H_ID,
                                            H_PRICE: successData[j].H_PRICE,
                                            H_AMOUNT: oldRows[i].H_AMOUNT,
                                            AMOUNT: successData[j].H_AMOUNT,
                                            //H_TAOZHUANG: successData[j].H_TAOZHUANG,
                                            //C_CODE: successData[j].C_CODE,
                                            STOCK_AMOUNT: successData[j].STOCK_AMOUNT,
                                            SORT_NUMBER: i + 1
                                        };
                                        cindex++;
                                        successData.splice(j, 1);
                                        j = 0;
                                        $('#' + flg + '_addItemDatagrid').datagrid('addChangeRow', oldRows[i]);
                                    }
                                }
                            }
                            for (var i = 0, len = successData.length; i < len; i++) {
                                successData[i].SORT_NUMBER = i;
                                dg.datagrid('appendRow', successData[i]);
                                commonMxRowCalcu(flg + "_addItemDatagrid", oldRows.length - 1);
                            }
                            //// 调用单品多行方法
                            //if (rows.length > 0) {
                            //    inputNumber(rows, flg, dsId[0]);
                            //}
                            //当再次导入excel时，数量累加的弹框显示出来，点击确定后弹框关闭
                            if (rows.length > 0) {
                                inputNumber1(rows, flg, dsId[0]);
                            }
                        } else {
                            for (var i = 0, len = successData.length; i < len; i++) {
                                dg.datagrid('appendRow', successData[i]);
                                commonMxRowCalcu(flg + "_addItemDatagrid", oldRows.length - 1);
                            }
                        }
                        var jsparam = eval("window.parent." + (dsId.split(";")[0]) + "_cfxjs"); // 加载计算参数
                        if (jsparam != undefined && jsparam != null && jsparam != "") {
                            commonMxTotalCalcu(jsparam, flg + "_addItemDatagrid");
                        }
                    }

                    // 去掉蒙板
                    mask_kkk.remove();
                    mask_kk.remove();
                    // 如果 错误数据的长度是0 就关闭窗口
                    if (obj.bad != undefined && obj.bad.length == 0) {
                        $('#IMP_EXC_PARENT_PANEL').window('close');
                    }
                    // 去除 加载效果后,如果有消息的话 就提示
                    if (obj.errmsg != undefined) {
                        alert(obj.errmsg);
                    }
                    /*
                     * } catch(e){ alert(e.name); alert(e.stack);
                     * alert(e.lineNumber); alert(e.message);
                     *
                     * description: 错误描述 (仅IE可用). fileName: 出错的文件名 (仅Mozilla可用).
                     * lineNumber: 出错的行数 (仅Mozilla可用). message: 错误信息
                     * (在IE下同description) name: 错误类型. number: 错误代码 (仅IE可用). stack:
                     * 像Java中的Stack Trace一样的错误堆栈信息 (仅Mozilla可用). }
                     */
                }// 结束响应成功
            });
        } else {
            $.messager.alert('警告', '文件必须为Excel文件');
        }
    } else {
        $.messager.alert('警告', '上传文件不允许为空');
    }

}





